<template>
  <div class="container-fluid p-4">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="6">
        <el-card class="stats-card" shadow="hover">
          <div class="d-flex align-items-center">
            <i class="bi bi-journal-check text-primary me-3"></i>
            <div>
              <div class="text-muted">我的考核</div>
              <h4 class="mb-0">{{ totalAssessments }}</h4>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card" shadow="hover">
          <div class="d-flex align-items-center">
            <i class="bi bi-person-check text-success me-3"></i>
            <div>
              <div class="text-muted">总参与人次</div>
              <h4 class="mb-0">{{ totalParticipants }}</h4>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card" shadow="hover">
          <div class="d-flex align-items-center">
            <i class="bi bi-question-circle text-warning me-3"></i>
            <div>
              <div class="text-muted">我的题库</div>
              <h4 class="mb-0">{{ totalQuestions }}</h4>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card" shadow="hover">
          <div class="d-flex align-items-center">
            <i class="bi bi-graph-up text-info me-3"></i>
            <div>
              <div class="text-muted">平均通过率</div>
              <h4 class="mb-0">{{ averagePassRate }}%</h4>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 筛选和操作 -->
    <el-card class="box-card mb-4" shadow="never">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="考核名称">
          <el-input v-model="searchForm.name" placeholder="请输入考核名称"></el-input>
        </el-form-item>
        <el-form-item label="考核类型">
          <el-select v-model="searchForm.type" placeholder="请选择考核类型">
            <el-option label="全部" value=""></el-option>
            <el-option label="理论考核" value="理论考核"></el-option>
            <el-option label="技能考核" value="技能考核"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考核状态">
          <el-select v-model="searchForm.status" placeholder="请选择考核状态">
            <el-option label="全部" value=""></el-option>
            <el-option label="进行中" value="进行中"></el-option>
            <el-option label="已结束" value="已结束"></el-option>
            <el-option label="未开始" value="未开始"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="onReset">重置</el-button>
          <el-button type="primary" @click="handleCreate">创建考核</el-button>

          <!-- <el-table :data="exams" v-loading="loading" style="width: 100%">
            <el-table-column label="操作" width="180">
              <template #default="{ row }">
                <el-button size="small" @click="handleEdit(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(row.exam.id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table> -->
          <el-button type="info" @click="modalController.openPopup('questionBankModal')">我的题库
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 考核列表 -->
    <el-row>
      <el-col :span="24">
        <el-card class="box-card" shadow="never">
          <template #header>
            <div class="card-header">
              <h5>考核列表</h5>
            </div>
          </template>
          <el-table :data="paginatedAssessments" style="width: 100%"
            :default-sort="{ prop: 'exam.startTime', order: 'descending' }" stripe>
            <el-table-column prop="exam.title" label="考核名称" width="180"></el-table-column>
            <el-table-column prop="exam.examType" label="类型" width="120"></el-table-column>
            <el-table-column prop="exam.status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.exam.status)">{{ scope.row.exam.status }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column prop="exam.createTime" label="创建日期" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.exam.createTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="exam.startTime" label="开始时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.exam.startTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="exam.endTime" label="结束时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.exam.endTime) }}
              </template>
            </el-table-column>
            <!-- 参与人数和通过率在当前数据结构中没有直接对应的字段，暂时注释掉 -->
            <!--
            <el-table-column
              prop="participants"
              label="参与人数"
              width="100"
            ></el-table-column>
            <el-table-column
              prop="passRate"
              label="通过率"
              width="100"
            ></el-table-column>
            -->
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.row)">编辑
                </el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination @size-change="handleSizeChange" @current-change="handlePageChange" :current-page="currentPage"
            :page-size="pageSize" :total="totalAssessments" layout="prev, pager, next" background
            class="mt-4 justify-content-center"></el-pagination>
        </el-card>
      </el-col>
    </el-row>
  </div>

  <NewAssessmentModal v-model="modalController.popups.newAssessmentModal" @refresh="refreshTable" />
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { modalControllers } from "@/stores/modalController.js";
import NewAssessmentModal from "@/components/alert/teacher/NewAssessmentModal.vue";
import { onMounted } from 'vue';
import { useUserStore } from "@/stores/user.js";
import { useExamStore } from '@/stores/exam.js';
import { storeToRefs } from 'pinia';
const modalController = modalControllers();
const examStore = useExamStore();
const userStore = useUserStore();
userStore.selectTeacherCourse(userStore.user.id);
userStore.selectTeacherExam("李老师");

// 从 store 中获取响应式的考核列表和加载状态
const { exams, loading } = storeToRefs(examStore);

// 组件加载时，获取第一页的考核数据
onMounted(() => {
  const userStore = useUserStore();
  console.log("name:", userStore.user.name);
  examStore.fetchExams({ pageNum: 1, pageSize: 10, creatorName: userStore.user.name });
  console.log("data:", examStore.exams);
});

// 处理“创建考核”按钮点击
const handleCreate = () => {
  modalController.editingExam = null; // 清空编辑状态
  modalController.newAssessmentModalVisible = true; // 打开弹窗
};

// 处理“编辑”按钮点击
const handleEdit = (row) => {
  // 从API返回的数据结构中，考核信息在 .exam 对象里
  modalController.editingExam = row.exam;
  modalController.newAssessmentModalVisible = true; // 打开弹窗
};


const searchForm = reactive({
  name: "",
  type: "",
  status: "",
});
// 添加刷新方法
const refreshTable = () => {
  userStore.selectTeacherExam(); // 重新从store加载数据
};
const assessments = computed(() => {
  console.log("assessments (from teacher_myExam):", userStore.teacher_myExam);
  // 确保 userStore.teacher_myExam 是一个数组，如果不是则返回空数组
  return Array.isArray(userStore.teacher_myExam)
    ? userStore.teacher_myExam
    : [];
});

const currentPage = ref(1);
const pageSize = ref(10);

const filteredAssessments = computed(() => {
  return assessments.value.filter((item) => {
    const nameMatch =
      !searchForm.name || item.exam.title.includes(searchForm.name);
    const typeMatch =
      !searchForm.type || item.exam.examType === searchForm.type;
    const statusMatch =
      !searchForm.status || item.exam.status === searchForm.status;
    return nameMatch && typeMatch && statusMatch;
  });
});

const paginatedAssessments = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredAssessments.value.slice(start, end);
});

const totalAssessments = computed(() => assessments.value.length);
const totalParticipants = computed(() => 0); // 暂时设置为0，因为后端数据中没有直接的参与人数
const totalQuestions = computed(() => 0); // 暂时设置为0，因为后端数据中没有直接的题库数量
const averagePassRate = computed(() => "0"); // 暂时设置为0，因为后端数据中没有直接的通过率

const getStatusType = (status) => {
  switch (status) {
    case "published":
      return "success"; // 已发布
    case "draft":
      return "warning"; // 草稿
    default:
      return "info";
  }
};

const onSearch = () => {
  currentPage.value = 1;
  // In a real application, you would fetch data from the backend here
  console.log("搜索条件:", searchForm);
};

const onReset = () => {
  searchForm.name = "";
  searchForm.type = "";
  searchForm.status = "";
  currentPage.value = 1;
  // In a real application, you would re-fetch data from the backend here
};

// const handleEdit = async (row) => {
//   await userStore.updateExam(row.exam);
//   ElMessage.info(`编辑考核: ${row.exam.title}`);
//   // Implement edit logic, e.g., open a dialog with row data
// };

const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除考核 "${row.exam.title}" 吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const success = examStore.deleteExam(examId);
      if (success) {
        // 如果store返回成功，重新获取列表以刷新界面
        examStore.fetchExams({ pageNum: 1, pageSize: 10 });
      }
    });
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  console.log(`${val} items per page`);
};

const handlePageChange = (val) => {
  currentPage.value = val;
  console.log(`current page: ${val}`);
};

const formatDate = (dateString) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
</script>

<style scoped>
.stats-card {
  .bi {
    font-size: 2.5rem;
  }
}

.search-input {
  max-width: 250px;
}

.el-pagination {
  justify-content: flex-end;
}

.assessment-card {
  .card-header {
    background-color: var(--el-fill-color-light);
    padding: 10px 20px;
    border-bottom: 1px solid var(--el-border-color-light);
    border-radius: var(--el-border-radius-base) var(--el-border-radius-base) 0 0;
  }
}
</style>
